﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using ProjectLib;

namespace Server
{
    [Serializable]
    public class ServerConnectionManager
    {
        private static ServerConnectionManager instance;
        private Socket socket;
        private Thread serverThread;
        private NetworkStream stream;
        private MainRequestManager mrm;
        public static ServerConnectionManager Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new ServerConnectionManager();
                }
                return instance;
            }
        }

        private ServerConnectionManager()
        {
            try
            {
                mrm = MainRequestManager.Instance;
                serverThread = new Thread(new ThreadStart(this.Listen));
            }
            catch (ConnectionException)
            {
                throw;
            }
        }

        public void StartServer()
        {
            serverThread.Start();
        }

        public void StopServer()
        {
            mrm.NotifyAllUsers();
            serverThread.Abort();
        }

        private void Listen()
        {
            TcpListener listener;
            IPAddress ipa;
            try
            {
                ipa = IPAddress.Parse(ProjectSettings.Default.Hostname);
            }
            catch (System.ArgumentNullException)
            {
                throw (new ConnectionException("ipString is null"));
            }
            catch (System.FormatException)
            {
                throw (new ConnectionException("ipString is not a valid IP address"));
            }
            try
            {
                listener = new TcpListener(ipa, ProjectSettings.Default.Port);
                listener.Start();

                while (true)
                {
                    while (!listener.Pending())
                    {
                        Thread.Sleep(1000);
                    }
                    socket = listener.AcceptSocket();
                    stream = new NetworkStream(socket);
                    UserRequestManager urm = new UserRequestManager(socket, stream);
                }
            }
            catch (System.ArgumentNullException)
            {
                throw (new ConnectionException("Failed to get data from client"));
            }
            catch (System.ArgumentOutOfRangeException)
            {
                throw (new ConnectionException("Failed to get data from client"));
            }
            catch (System.Net.Sockets.SocketException)
            {
                throw (new ConnectionException("Failed to get data from client"));
            }
        }
    }
}
